use strict;

opendir(ROOTDIR, ".");
my @locales = grep { !/^\.\.?$/ && !/^en-US$/ } readdir(ROOTDIR);
closedir(ROOTDIR);

#print join("\n", @locales), "\n";

opendir(BASEDIR, "en-US");
my @basefiles = grep { !/^\.\.?$/ } readdir(BASEDIR);
closedir(BASEDIR);

#print join("\n", @basefiles), "\n";


my %rowsmap = ();
foreach my $basefile (@basefiles) {
	open(BASEFILE, "<en-US/$basefile");
	
	while (<BASEFILE>) {
		if (!/^\s*$/) {
			if ($basefile =~ /dtd$/) {
				if (/ENTITY\s+(.*?)\s+/) {
					$rowsmap{$basefile}{$1} = $_;
				}
			}
			elsif ($basefile =~ /properties$/) {
				if (/^\s*(.*?)\s*\=/) {
					$rowsmap{$basefile}{$1} = $_;
				}
			}
		}
	}
	
	my @k = keys %{$rowsmap{$basefile}};
	print "$basefile: ", scalar @k, "\n";
	
	close(BASEFILE);
}

foreach my $locale (@locales) {
	foreach my $basefile (@basefiles) {
		print "$locale, $basefile: ";
		
		open(LOCALEFILE1, "<$locale/$basefile");

		my %rowsmap2 = ();
		while (<LOCALEFILE1>) {
			if (!/^\s*$/) {
				if ($basefile =~ /dtd$/) {
					if (/ENTITY\s+(.*?)\s+"(.*?)"/) {
						if ($2 ne "") {
							$rowsmap2{$basefile}{$1} = $_;
						}
					}
				}
				elsif ($basefile =~ /properties$/) {
					if (/^\s*(.*?)\s*\=\s*(.*)/) {
						if ($2 ne "") {
							$rowsmap2{$basefile}{$1} = $_;
						}
					}
				}
			}
		}
			
		close(LOCALEFILE1);

		my @k = keys %{$rowsmap{$basefile}};
		my @matchlist = grep { ! exists $rowsmap2{$basefile}{$_} } @k;
		
		print scalar @matchlist, " of ", scalar @k, "\n";

		# If missing strings...		
		if (scalar @matchlist) {
			# Add missing rows.
			foreach my $rowId (@matchlist) {
				$rowsmap2{$basefile}{$rowId} = $rowsmap{$basefile}{$rowId};
			}
			
			my @rows = values %{$rowsmap2{$basefile}};
			
			open(LOCALEFILE2, ">$locale/$basefile") || die;
			
			foreach my $row (sort @rows) {
				print LOCALEFILE2 $row;
			}
			
			close(LOCALEFILE2);
		}
	}
}